package com.hefeng.wx.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hefeng.common.core.domain.MapEntity;
import com.hefeng.common.core.utils.AmapUtil;
import com.hefeng.common.core.utils.DateUtils;
import com.hefeng.wx.common.StartLoadingParameter;
import com.hefeng.wx.domain.WxDevice;
import com.hefeng.wx.domain.WxDeviceUser;
import com.hefeng.wx.domain.WxUser;
import com.hefeng.wx.domain.gas.GasDeviceInfo;
import com.hefeng.wx.mapper.WxDeviceMapper;
import com.hefeng.wx.mapper.WxDeviceUserMapper;
import com.hefeng.wx.mapper.WxUserMapper;
import com.hefeng.wx.service.WxDeviceService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import com.hefeng.common.core.utils.EmptyUtils;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class WxDeviceServiceImpl extends ServiceImpl<WxDeviceMapper, WxDevice> implements WxDeviceService  {
    @Autowired
    private WxDeviceMapper wxDeviceMapper;
    @Autowired
    private WxDeviceUserMapper wxDeviceUserMapper;
    @Autowired
    private WxUserMapper wxUserMapper;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 新增数据
     * @param wxDevice 实例对象
     * @return 实例对象
     */
    public Map<String,Object> insert(WxDevice wxDevice){
        Map<String,Object> dataMap=new HashMap<>();
        //查询设备code是否存在
        if(StrUtil.isBlank(wxDevice.getDeviceCode())){
            dataMap.put("make",false);
            dataMap.put("msg","设备code不能为空！");
            return dataMap;
        }
        //验证设备是否添加到采集平台
       JSONObject obj=restTemplate.getForObject(StartLoadingParameter.QUERYBYDEVICECODE+wxDevice.getDeviceCode(), JSONObject.class);
        if(!obj.has("obj")){
            dataMap.put("make",false);
            dataMap.put("msg","未查询到该设备，请联系运维人员！");
            return dataMap;
        }
        //验证设备是否在录入
        LambdaQueryWrapper<WxDeviceUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WxDeviceUser::getDeviceCode,wxDevice.getDeviceCode());
        queryWrapper.eq(WxDeviceUser::getIsDelete,"1");
        //只能一个人添加设备
       //queryWrapper.eq(WxDeviceUser::getUserId,wxDevice.getUserId());
        WxDeviceUser deviceUser=wxDeviceUserMapper.selectOne(queryWrapper);
        if (EmptyUtils.isNotEmpty(deviceUser)){
            dataMap.put("make",false);
            dataMap.put("msg","设备已存在！");
            return dataMap;
        }
        //获取设备城市编码
        MapEntity gas=AmapUtil.getTowncodeByLocation(wxDevice.getDeviceLongitude(),wxDevice.getDeviceLatitude());
        wxDevice.setCitycode(gas.getCitycode());
        wxDevice.setAdcode(gas.getAdcode());
        wxDevice.setTowncode(gas.getTowncode());
        //设备型号
        wxDevice.setDeviceModel("安可信");
        //厂家信息
        wxDevice.setManufacturerCode("");
        wxDevice.setDeviceManufacturer("安可信");
        //设备阈值
        wxDevice.setDeviceLimitValue("%7LEL");
        //是否删除;（1：正常  2：删除）
        wxDevice.setIsDeleted(1);
        //设备缩略图
        wxDevice.setDeviceThumPic("https://hefengzhxf.oss-cn-guangzhou.aliyuncs.com/gas/3c102b4282157cd89f9e8f53b4f1335.png");
        //创建时间
        wxDevice.setCreatedTime(new Date());
        //设备激活时间
        wxDevice.setDeviceActiveTime(new Date());
        //设备报废时间
        wxDevice.setDeviceScrapTime(DateUtils.addYear(new Date(),3));
        int i=wxDeviceMapper.insert(wxDevice);
        //添加用户关联表
        WxDeviceUser wxDeviceUser=new WxDeviceUser();
        WxUser user=wxUserMapper.selectById(wxDevice.getUserId());
        wxDeviceUser.setPhone(user.getPhone());
        wxDeviceUser.setUserId(wxDevice.getUserId());
        wxDeviceUser.setDeviceCode(wxDevice.getDeviceCode());
        wxDeviceUser.setDeviceId(wxDevice.getDeviceId());
        wxDeviceUser.setOwnerUser(wxDevice.getUserId());
        wxDeviceUser.setIsDelete(1);
        wxDeviceUser.setCreatedTime(new Date());
        wxDeviceUserMapper.insert(wxDeviceUser);

        //添加成功后同步到燃气公司平台
        GasDeviceInfo gasDeviceInfo=new GasDeviceInfo();
        //设备编码
        gasDeviceInfo.setDeviceCode(wxDevice.getDeviceCode());
        //经度
        gasDeviceInfo.setLongitude(Double.parseDouble(wxDevice.getDeviceLongitude()));
        //经度
        gasDeviceInfo.setLatitude(Double.parseDouble(wxDevice.getDeviceLatitude()));
        //0.工业端 1.居民端
        gasDeviceInfo.setDeviceInstallationType("1");
        //市编码
        gasDeviceInfo.setCity(wxDevice.getCitycode());
        //设备名称
        gasDeviceInfo.setDeviceName(wxDevice.getDeviceName());
        //区域编码
        gasDeviceInfo.setDistrict(wxDevice.getAdcode());
        //街道编码
        gasDeviceInfo.setStreet(wxDevice.getTowncode());
        //设备安装地址
        gasDeviceInfo.setDeviceAddress(wxDevice.getDeviceAddress());
        //小区名称
        gasDeviceInfo.setDeviceRemarks(user.getResidenceName());
        restTemplate.put(StartLoadingParameter.DEVICEUPDATEINFO,gasDeviceInfo);
        dataMap.put("make",true);
        return dataMap;
    }

    @Override
    public List<Map> getDeviceList(String userId, long current, long size) {
        if(EmptyUtils.isEmpty(userId)){
            return null;
        }
        List<Map> list =new ArrayList<>();
        list=wxDeviceMapper.selectDeviceList(Long.parseLong(userId));
        return list;
    }

    @Override
    public Map<String, Object> update(WxDevice wxDevice) {
        Map<String,Object> dataMap=new HashMap<>();
        try {
        //1. 根据条件动态更新
        LambdaQueryWrapper<WxDevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WxDevice::getDeviceId,wxDevice.getDeviceId());
        //获取设备城市编码
        MapEntity gas=AmapUtil.getTowncodeByLocation(wxDevice.getDeviceLongitude(),wxDevice.getDeviceLatitude());
        wxDevice.setCitycode(gas.getCitycode());
        wxDevice.setAdcode(gas.getAdcode());
        wxDevice.setTowncode(gas.getTowncode());
        wxDeviceMapper.update(wxDevice,queryWrapper);
        WxDevice device=wxDeviceMapper.selectOne(queryWrapper);

            GasDeviceInfo gasDeviceInfo=new GasDeviceInfo();
            //设备编码
            gasDeviceInfo.setDeviceCode(wxDevice.getDeviceCode());
            //经度
            gasDeviceInfo.setLongitude(Double.parseDouble(wxDevice.getDeviceLongitude()));
            //经度
            gasDeviceInfo.setLatitude(Double.parseDouble(wxDevice.getDeviceLatitude()));
            //0.工业端 1.居民端
            gasDeviceInfo.setDeviceInstallationType("1");
            //市编码
            gasDeviceInfo.setCity(wxDevice.getCitycode());
            //设备名称
            gasDeviceInfo.setDeviceName(wxDevice.getDeviceName());
            //区域编码
            gasDeviceInfo.setDistrict(wxDevice.getAdcode());
            //街道编码
            gasDeviceInfo.setStreet(wxDevice.getTowncode());
            //设备安装地址
            gasDeviceInfo.setDeviceAddress(wxDevice.getDeviceAddress());
            //小区名称
            restTemplate.put(StartLoadingParameter.DEVICEUPDATEINFO,gasDeviceInfo);


        dataMap.put("make",true);
        dataMap.put("device",device);
        }catch (Exception e){
            dataMap.put("msg","修改失败！");
        }
        return dataMap;
    }

    @Override
    public Map<String, Object> deleteDevice(String deviceId) {
        Map<String, Object> data=new HashMap<>();
        try {
        LambdaQueryWrapper<WxDeviceUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WxDeviceUser::getDeviceId,deviceId);
        WxDeviceUser wxDeviceUser=new WxDeviceUser();
        wxDeviceUser.setIsDelete(2);
        wxDeviceUserMapper.update(wxDeviceUser,queryWrapper);
            data.put("make",true);
        }catch (Exception e){
            data.put("make",false);
            data.put("msg","删除失败！");

        }

        return data;
    }
}
